<template>
  <BasicModal v-bind="$attrs" @register="registerModal" :title="getTitle" @ok="handleSubmit">
    <BasicForm @register="registerForm">
      <template #code="{ model }">
        <a-input
          v-model:value="model.number"
          placeholder="请输入供应商编码"
          :readonly="model.isSysNumBoolean"
        />
      </template>
      <template #isSysNumBoolean="{ model }">
        <a-checkbox v-model:checked="model.isSysNumBoolean" @change="handleSysChange">
          用系统编号
        </a-checkbox>
      </template>
    </BasicForm>
  </BasicModal>
</template>
<script lang="ts" setup>
  import { ref, computed, unref } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { FormSchema } from '/@/components/Table';
  import {
    getSupplierInfo,
    addSupplier,
    updateSupplier,
    getSupplierCode,
  } from '/@/api/erp/supplier/list';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useI18n } from '/@/hooks/web/useI18n';
  const { t } = useI18n();
  const FormSchema: FormSchema[] = [
    {
      field: 'number',
      label: '供应商编码',
      component: 'Input',
      slot: 'code',
      rules: [
        {
          required: true,
          validator: (_, value) => {
            if (getFieldsValue().isSysNumBoolean) return Promise.resolve();
            if (value === '') {
              return Promise.reject('请输入供应商编码');
            } else if (!/^[0-9a-zA-Z_]{6,15}$/.test(value)) {
              return Promise.reject('请输入由6-15位的数字、字母、下划线组成的字符串');
            } else {
              return Promise.resolve();
            }
          },
        },
      ],
      colProps: { span: 18 },
    },
    {
      field: 'isSysNumBoolean',
      label: '',
      component: 'Input',
      slot: 'isSysNumBoolean',
      required: true,
      colProps: { span: 5, offset: 1 },
    },
    {
      field: 'name',
      label: '供应商名称',
      component: 'Input',
      required: true,
      colProps: { span: 24 },
      componentProps: {
        placeholder: '请输入供应商名称',
      },
    },
    {
      field: 'scope',
      label: '经营范围',
      component: 'Input',
      required: true,
      colProps: { span: 24 },
      componentProps: {
        placeholder: '请输入经营范围',
      },
    },
    {
      field: 'person',
      label: '负责人',
      component: 'Input',
      required: true,
      colProps: { span: 24 },
      componentProps: {
        placeholder: '请输入负责人',
      },
    },
    {
      field: 'phone',
      label: '手机号',
      component: 'Input',
      required: true,
      colProps: { span: 24 },
      componentProps: {
        placeholder: '请输入手机号',
      },
    },
    // {
    //   field: 'type',
    //   label: '供应商类别',
    //   component: 'Select',
    //   required: true,
    //   colProps: { span: 24 },
    //   componentProps: {
    //     placeholder: '请选择供应商类别',
    //     mode: 'multiple',
    //     options: [
    //       { label: '原料', value: '1' },
    //       { label: '成品', value: '2' },
    //       { label: '半成品', value: '3' },
    //       { label: '其他', value: '4' },
    //     ],
    //   },
    // },
    {
      field: 'type',
      label: '供应商类别',
      component: 'DicSelect',
      required: true,
      colProps: { span: 24 },
      componentProps: {
        placeholder: '请选择供应商类别',
        mode: 'multiple',
        itemId: '1676483934342787074',
        isShowAdd: false,
      },
    },
  ];

  const { notification } = useMessage();
  const isUpdate = ref(true);
  const rowId = ref('');
  const modalTitle = ref('');
  const emit = defineEmits(['success', 'register']);

  const [registerForm, { setFieldsValue, resetFields, validate, getFieldsValue }] = useForm({
    labelWidth: 100,
    schemas: FormSchema,
    showActionButtonGroup: false,
    actionColOptions: {
      span: 23,
    },
  });

  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    resetFields();
    setModalProps({ confirmLoading: false, destroyOnClose: true });

    isUpdate.value = !!data?.isUpdate;
    modalTitle.value = data.title;
    if (unref(isUpdate)) {
      rowId.value = data.id;
      const record = await getSupplierInfo(data.id);
      record.type = record.type?.split(',') as any;
      setFieldsValue({
        ...record,
      });
    } else {
      const materialCode = await getSupplierCode();
      setFieldsValue({ number: materialCode, isSysNumBoolean: true });
    }
  });

  const getTitle = computed(() =>
    !unref(isUpdate) ? `新增${modalTitle.value}供应商` : `编辑${modalTitle.value}供应商`,
  );

  const handleSysChange = async (e) => {
    let materialCode = '';
    if (e.target.checked) {
      materialCode = await getSupplierCode();
    }
    setFieldsValue({ number: materialCode });
  };

  const handleSubmit = async () => {
    try {
      const values = await validate();
      setModalProps({ confirmLoading: true });
      values.type = values.type.toString();
      if (!unref(isUpdate)) {
        await addSupplier(values);
        notification.success({
          message: `新增${modalTitle.value}供应商`,
          description: t('成功'),
        });
      } else {
        values.id = rowId.value;
        await updateSupplier(values);
        notification.success({
          message: `编辑${modalTitle.value}供应商`,
          description: t('成功'),
        });
      }

      closeModal();
      emit('success');
    } catch (error) {
      setModalProps({ confirmLoading: false });
    }
  };
</script>
